<template>
    <div class="feedbackContainer">
        <el-header>
            <img class="pull-left" width="58px" src="../../assets/images/djlogo.png" alt="">
            <span>洞见云 意见反馈</span>
        </el-header>
        <div class="feedback">
            <el-form :model="saveForm" :rules="rules" ref="saveForm">
                <el-form-item label="类型" prop="type">
                    <el-radio-group v-model="saveForm.type">
                        <el-radio :label="1">程序错误</el-radio>
                        <el-radio :label="2">产品建议</el-radio>
                        <el-radio :label="3">其他</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="反馈内容" prop="remark">
                    <el-input v-model="saveForm.remark" type="textarea" :rows=10 :maxlength="200" placeholder="您的反馈将帮助我们更快的成长"></el-input>
                </el-form-item>
                <span style="color:#dcdfe6;position: relative;top:-46px;right: 20px;" class="pull-right">{{saveForm.remark.length}}/200</span>
            </el-form>
            <div style="color:#606266;font-size: 14px;margin-bottom:15px;">上传图片：(选填，最多只能上传{{imglimit}}张)</div>
            <div class="file-list">
                <el-upload drag :multiple="multiple" action="123" list-type="picture-card" :auto-upload="false"
                    :http-request="uploadFile" :limit=imglimit ref="upload">
                    <i class="el-icon-plus"></i>
                </el-upload>
            </div>
            <el-button class="pull-right" type="primary" :loading="loading" @click="saveClick('saveForm')">提 交</el-button>
        </div>
    </div>
</template>
<script>
    import {
        getSts, save
    } from "@/api/feedback";
    import axios from 'axios';
    export default {
        data() {
            return {
                multiple: true,
                loading: false,
                uid: '',
                formDate: '',
                imgList: [],
                imglimit: 3,
                saveForm: {
                    from: '', //1 APP 2 WEB 3 PC',
                    remark: '',
                    type: '',
                    uid: '',
                    img_list: []
                },
                rules: {
                    remark: [
                        { required: true, message: '请输入反馈内容', trigger: 'blur' },
                    ],
                    type: [
                        { required: true, message: '请选择类型', trigger: 'change' }
                    ],
                }
            }
        },
        created() {
            console.log(this.$route.from)
            this.saveForm.from = this.$route.params.from;
            let _id = this.$route.params._id;
            console.log(Base64.decode(_id))
            this.saveForm.uid = Base64.decode(_id).split('_')[0];
            this.saveForm.uname = Base64.decode(_id).split('_')[1];
        },
        methods: {
            uploadFile(file) {
                this.imgList.push({ 'file': file.file })
            },
            saveClick(formName) {
                console.log(this.saveForm)
                if (!this.saveForm.uid || !this.saveForm.uname || !this.saveForm.from*1>3) {
                    this.$message({ type: 'error', message: 'URL参数不合法，请关闭后重新从系统跳转到此页面' });
                    return;
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.saveImg();//上傳OSS
                    }
                });
            },
            saveImg() {
                this.$refs.upload.submit();
                if (this.imgList.length == 0) {
                    this.saveAll();
                    return;
                }
                this.loading = true
                getSts({}, this.saveForm.from).then(response => {
                    let host = 'http://src-scfy.oss-cn-hangzhou.aliyuncs.com';
                    let policyText = {
                        "expiration": "2050-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
                        "conditions": [
                            ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
                        ]
                    };
                    let policyBase64 = Base64.encode(JSON.stringify(policyText))
                    let bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, response.AccessKeySecret, { asBytes: true });
                    let signature = Crypto.util.bytesToBase64(bytes);
                    let config = {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }
                    let date = new Date();
                    let dateYMD = `${date.getFullYear()}${date.getMonth()}${date.getDate()}`
                    let dateHMS = `${date.getHours()}${date.getMinutes()}${date.getSeconds()}`
                    let dirName = location.host == 'scfy.i3020.com' ? '' : '/test_sms'
                    for (let i = 0; i < this.imgList.length; i++) {
                        let data = new FormData()
                        let imgName = `feedback${dirName}/${dateYMD}/${dateYMD}${dateHMS}${this.S4()}.png`
                        data.append('key', imgName);
                        data.append('policy', policyBase64);
                        data.append('OSSAccessKeyId', response.AccessKeyId);
                        data.append('success_action_status', 200);
                        data.append('x-oss-security-token', response.SecurityToken);
                        data.append('signature', signature);
                        data.append('file', this.imgList[i].file);
                        axios.post(host, data, config).then(res => {
                            this.saveForm.img_list.push({ name: imgName })
                            if (i == this.imgList.length - 1) {
                                console.log(this.saveForm)
                                this.saveAll();//提交全部信息
                            }
                        }).catch(res => {
                            this.$message({ type: 'error', message: JSON.stringify(res) });
                            console.log(res)
                        })
                    }
                })
            },
            saveAll() {
                save(this.saveForm).then(response => {
                    if (response.code == 1) {
                        this.$message({ type: 'success', message: response.message });
                        this.$alert('感谢您的反馈，我们会尽快处理', response.message, {
                            confirmButtonText: '确定',
                            callback: action => {
                                location.reload();
                            }
                        });
                    }
                })
            },
            S4() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            },
        }
    }
</script>
<style rel="stylesheet/scss" lang="scss">
    body {
        background: #eff3f5;
        overflow-y: auto;
    }

    .el-header {
        border-bottom: 1px solid #eee;
        line-height: 60px;
        font-size: 24px;
        background: #fff;
    }

    .feedback {
        width: 100%;
        max-width: 980px;
        margin: 15px auto;
        padding: 15px 15px 60px 15px;
        background: #fff;
        border-radius: 4px;
    }

    .el-upload-dragger {
        height: inherit;
        width: inherit;
    }
</style>